package com.mainbo.androidframework.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import com.mainbo.androidframework.App;

/**
 * 跟手机相关类
 * Created by lsmtty on 2016/3/3.
 */
public class PhoneUtils {
    private static Context mContext = App.mContext;
    public static final int SIMPLIFIED_CHINESE = 0;
    public static final int TRADITIONAL_CHINESE = 1;
    public static final int ENGLISH = 2;
    private static final String TAG = PhoneUtils.class.getSimpleName();
    /**
     * 版本号段数<br>
     * 如：3.2.253
     */
    private static final int VER_LEN = 3;

    private static int[] VER = new int[VER_LEN];

    /**
     * 版本名称,android版本名:2.1.0.50833,最后一段50833是app的版本号.
     */
    private static String versionName;

    /**
     * 版本号.
     */
    private static int versionCode;

    /**
     * 设备Id.
     */
    private static String deviceId;

    /**
     * MAC地址.
     */
    private static String macAddress;

    /**
     * 设备唯一id,根据deviceId,MAC等信息生成.
     */
    private static String deviceUniqueId;

    /**
     * 设备ID.DeviceId,MAC,AndroidId,BuildInfo,如果取不到,依次用上述信息替代.
     */
    public static String getDeviceId() {
        if (deviceId == null) {
            String devideInfo = null;
            // DeviceId
            devideInfo = PhoneUtils.getDeviceIdFromSystem();
            if (TextUtils.isEmpty(devideInfo)) {
                // MAC
                devideInfo = PhoneUtils.getMacAddress();
                if (TextUtils.isEmpty(devideInfo)) {
                    // AndroidId
                    devideInfo = getAndroidId();
                    // BuildInfo
                    if (TextUtils.isEmpty(devideInfo)) {
                        devideInfo = PhoneUtils.getBuildInfo();
                    }
                }
            }
            deviceId = devideInfo;
            LogUtil.i(TAG, "getDeviceId deviceId:" + deviceId);
        }
        return deviceId;
    }

    /**
     * get deviceid
     *
     * add <uses-permission android:name="READ_PHONE_STATE" />
     *
     * @return
     */
    private static String getDeviceIdFromSystem() {
        String deviceId = "";
        if (PhoneUtils.checkPhoneState(mContext)) {
            TelephonyManager tm = (TelephonyManager) mContext
                    .getSystemService(Context.TELEPHONY_SERVICE);
            deviceId = tm.getDeviceId();
        }
        LogUtil.i(TAG, "getDeviceIdFromSystem deviceId:" + deviceId);
        return deviceId;
    }

    /**
     * Get the version number of the current program
     *
     * @param
     * @return
     */

    public static String getVersionNameFromSystem() {
        String curversion = "";
        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), 0);
            curversion = pi.versionName;
            if (curversion == null || curversion.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curversion;
    }

    /**
     * 客户端版本名称.
     *
     * @return
     */
    public static String getVersionName() {
        if (versionName == null) {
            versionName = PhoneUtils.getVersionNameFromSystem();
        }
        return versionName;
    }

    /**
     * 客户端版本号.
     *
     * @return
     */
    public static int getVersionCode() {
        if (versionCode <= 0) {
            versionCode = getVersionCodeFromSystem();
        }
        return versionCode;
    }

    private static int getVersionCodeFromSystem() {
        PackageManager pm = mContext.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = pm.getPackageInfo(mContext.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return packageInfo != null ? packageInfo.versionCode : -1;
    }

    /**
     * 获取MAC地址.
     *
     * @return
     */
    public static String getMacAddress() {
        if (macAddress == null) {
            macAddress = getMacAddressFromSystem();
        }
        return macAddress;
    }

    public static String getMacAddressFromSystem() {
        String macAddress = null;
        if (PhoneUtils.checkPermissions(mContext,
                "android.permission.ACCESS_WIFI_STATE")) {
            WifiManager wifiMgr = (WifiManager) mContext
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = (null == wifiMgr ? null : wifiMgr
                    .getConnectionInfo());
            if (null != info) {
                macAddress = info.getMacAddress();
            }
        }
        return macAddress;
    }

    /**
     * 获取运营商
     *
     * @param
     * @return
     */
    public static String getProvidersName() {
        String providersName = null;
        if (PhoneUtils.checkPermissions(mContext,
                "android.permission.READ_PHONE_STATE")) {
            TelephonyManager telephonyManager = (TelephonyManager) mContext
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String id = telephonyManager.getSubscriberId();
            if (id == null)
                return providersName;
            if (id.startsWith("46000") || id.startsWith("46002")) {
                providersName = "移动";
            } else if (id.startsWith("46001")) {
                providersName = "联通";
            } else if (id.startsWith("46003")) {
                providersName = "电信";
            }
        }
        return providersName;

    }

    /**
     * get sdk number
     *
     * @return sdk版本
     */
    public static String getSdkVersion() {
        String osVersion = "";
        if (PhoneUtils.checkPhoneState(mContext)) {
            osVersion = Build.VERSION.RELEASE;
        }
        LogUtil.i(TAG, "getSdkVersion OsVerson:" + osVersion);
        return osVersion;
    }

    /**
     * 获取设备的唯一标识ID(32位),
     *
     * @return
     */
    public static String getDeviceUniqueId() {
        if (deviceUniqueId == null) {
            String deviceId = getDeviceIdFromSystem();
            String buildInfo = PhoneUtils.getBuildInfo();
            String androidId = getAndroidId();
            String wlanMac = PhoneUtils.getMacAddress();
            String devideInfo = deviceId + buildInfo + androidId + wlanMac;
            String md5Str = MD5.encodeString(devideInfo, MD5.LONG_TYPE, false);
            deviceUniqueId = md5Str;
            LogUtil.i(TAG, "deviceUniqueId: " + deviceUniqueId);
        }
        return deviceUniqueId;
    }

    /**
     * 获取build信息
     *
     * @return
     */
    private static String getBuildInfo() {
        String buildInfo = "35" + Build.BOARD.length() % 10
                + Build.BRAND.length() % 10 + Build.CPU_ABI.length() % 10
                + Build.DEVICE.length() % 10 + Build.DISPLAY.length() % 10
                + Build.HOST.length() % 10 + Build.ID.length() % 10
                + Build.MANUFACTURER.length() % 10 + Build.MODEL.length() % 10
                + Build.PRODUCT.length() % 10 + Build.TAGS.length() % 10
                + Build.TYPE.length() % 10 + Build.USER.length() % 10;
        LogUtil.i(TAG, "getBuildInfo buildInfo:" + buildInfo);
        return buildInfo;
    }

    /**
     * 返回AndroidId.
     *
     * @return
     */
    private static String getAndroidId() {
        String androidId = Settings.Secure.getString(mContext.getContentResolver(),
                Settings.Secure.ANDROID_ID);
        LogUtil.i(TAG, "getAndroidId androidId:" + androidId);
        return androidId;
    }

    /**
     * Get device name, manufacturer + model
     *
     * @return device name
     */
    public static String getDeviceName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;

        if (model.startsWith(manufacturer)) {
            return PhoneUtils.capitalize(model);
        } else {
            return PhoneUtils.capitalize(manufacturer) + " " + model;
        }
    }

    /**
     * Capitalize the first letter
     *
     * @param s
     *            model,manufacturer
     * @return Capitalize the first letter
     */
    private static String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }

    /**
     * check phone _state is readied ;
     *
     * @param context
     * @return
     */
    public static boolean checkPhoneState(Context context) {
        return checkPermissions(context, "android.permission.READ_PHONE_STATE");
    }

    /**
     * checkPermissions
     *
     * @param context
     * @param permission
     * @return true or false
     */
    public static boolean checkPermissions(Context context, String permission) {
        PackageManager localPackageManager = context.getPackageManager();
        return localPackageManager.checkPermission(permission,
                context.getPackageName()) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 获取分辨率.
     *
     * @return
     */
    public static String getResolution() {
        DisplayMetrics dm = new DisplayMetrics();
        dm = mContext.getResources().getDisplayMetrics();
        return dm.widthPixels + "*" + dm.heightPixels;
    }

    // 判断存储卡是否可用
    public static  boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}
